package com.gzhryc.shared_device.cdb.api;

import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.cdb.api.protocol.*;
import com.gzhryc.shared_device.cdb.core.ICDBNetworkService;
import com.gzhryc.shared_device.cdb.core.models.CDBExecuteResult;
import com.gzhryc.shared_device.cdb.core.models.CDBLeaseCommand;
import com.gzhryc.shared_device.iot.core.IOTNodeEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

public class CDBHttpAPINetworkService implements ICDBNetworkService {

    private static Logger log = Logger.getLogger(CDBHttpAPINetworkService.class);

    private IOTNodeEntity iotNode;
    private CloseableHttpClient httpClient;

    public CDBHttpAPINetworkService(IOTNodeEntity iotNode) {
        this.iotNode = iotNode;
        this.httpClient = HttpClients.createDefault();
    }

    @Override
    public CDBExecuteResult lease(CDBLeaseCommand leaseCommand) {
        CDBExecuteResult result = new CDBExecuteResult(CDBExecuteResult.TIMEOUT);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/cdb/lease.do").build();

            CDBHttpLeaseRequest apiReq = new CDBHttpLeaseRequest();
            apiReq.getBody().setDeviceSn(leaseCommand.getDeviceSn());
            apiReq.getBody().setSlotNum(leaseCommand.getSlotNum());
            apiReq.getBody().setTradeNo(leaseCommand.getTradeNo());

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("共享充电宝租借返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CDBHttpLeaseResponse apiResp = JsonTools.fromJson(str, CDBHttpLeaseResponse.class);
                    if(apiResp != null) {
                        result.setCode(apiResp.getBody().getResultCode());
                        result.setMsg(apiResp.getBody().getErrorMsg());
                        result.setMessageId(apiResp.getBody().getMessageId());
                    }
                }
            }
        } catch(Exception e){
            log.error("共享充电宝租借错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDBExecuteResult forceEjectDevice(String deviceSn, Integer slotNum,String messageId) {
        CDBExecuteResult result = new CDBExecuteResult(CDBExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/cdb/eject.do").build();

            CDBHttpEjectRequest apiReq = new CDBHttpEjectRequest();
            apiReq.getBody().setDeviceSn(deviceSn);
            apiReq.getBody().setSlotNum(slotNum);
            apiReq.getBody().setMessageId(messageId);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("共享充电宝强制弹出返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CDBHttpEjectResponse apiResp = JsonTools.fromJson(str, CDBHttpEjectResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("共享充电宝强制弹出错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDBExecuteResult forceEjectDevice(String deviceSn,String messageId) {
        CDBExecuteResult result = new CDBExecuteResult(CDBExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/cdb/eject.do").build();

            CDBHttpEjectRequest apiReq = new CDBHttpEjectRequest();
            apiReq.getBody().setDeviceSn(deviceSn);
            apiReq.getBody().setMessageId(messageId);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("共享充电宝强制弹出返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CDBHttpEjectResponse apiResp = JsonTools.fromJson(str, CDBHttpEjectResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("共享充电宝强制弹出错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDBExecuteResult searchDevice(String deviceSn) {
        CDBExecuteResult result = new CDBExecuteResult(CDBExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/cdb/search.do").build();

            CDBHttpSearchRequest apiReq = new CDBHttpSearchRequest();
            apiReq.getBody().setDeviceSn(deviceSn);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("共享充电宝查询返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CDBHttpSearchResponse apiResp = JsonTools.fromJson(str, CDBHttpSearchResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("共享充电宝查询错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDBExecuteResult sendCmd(String deviceSn, String content) {
        CDBExecuteResult result = new CDBExecuteResult(CDBExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/cdb/send_cmd.do").build();

            CDBHttpSendCmdRequest apiReq = new CDBHttpSendCmdRequest();
            apiReq.getBody().setDeviceSn(deviceSn);
            apiReq.getBody().setContent(content);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("共享充电宝发送任意报文返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CDBHttpSendCmdResponse apiResp = JsonTools.fromJson(str, CDBHttpSendCmdResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("共享充电宝发送任意报文错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
